<template>
  <div class="article-container">
    <van-pull-refresh
      v-model="isRefresh"
      :success-text="refreshSuccessText"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="(article, index) in list" 
          :key="index" 
          :article="article" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import {getArticles} from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
  name: 'articleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isRefresh: false,
      refreshSuccessText: ''
    }
  },
  methods: {
    async onLoad() {
      try {
        const {data} = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })

        if(Math.random() < 0.1) {
          console.log(qwer)
        }

        const {results} = data.data

        this.list.push(...results)

        this.loading = false

        if(results.length !== 0) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch(err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        const {data} = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })

        const {results} = data.data

        this.list.unshift(...results)

        this.refreshSuccessText = '刷新成功'
        this.isRefresh = false

      } catch(err) {
        this.refreshSuccessText = '刷新失败'
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-container {
  height: 79vh;
  overflow-y: auto;
}
</style>
